package com.heima.search.service.impl;


import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IApUserSearchService;
import com.heima.search.service.IArticleSearchService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    ArticleRepository articleSearchService;

    @Autowired
    IApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) {

        QueryBuilder query = QueryBuilders.matchQuery("title", dto.getSearchWords());

        //   PageRequest page = PageRequest.of(dto.getPage().intValue() - 1, dto.getSize(), Sort.Direction.DESC, "publishTime");
        Pageable page = PageRequest.of(dto.getPage().intValue() - 1, dto.getSize(), Sort.Direction.DESC, "publishTime");

        Page<ApArticleSearch> search = articleSearchService.search(query, page);

        User user = AppThreadLocalUtil.get();

        Integer userId = null;

        if (user != null) {

            userId = user.getUserId();
        }
        apUserSearchService.saveSearchRecord(dto.getSearchWords(), userId, dto.getEquipmentId());

        return ResponseResult.okResult(search.getContent());
    }
}
